import mx.utils.Delegate;

import gugga.browser.BrowserHistory;
import gugga.commands.CommandManager;
import gugga.common.DeepLinksSerializer;
/**
 * TODO: Synchronize CommandHistory undo/redo state with BrowserHistory
 */
class gugga.browser.BrowserHistoryManager 
{
	private static var COMMAND_INDEX_KEY : String = "commandIndex";
	
	private static var mInstance : BrowserHistoryManager = null;
	
	private function BrowserHistoryManager()
	{
		super();
		
		BrowserHistory.Instance.addEventListener("changed", 
			Delegate.create(this, onBrowserHistoryChanged));
		CommandManager.Instance.addEventListener("commandBufferContentChanged", 
			Delegate.create(this, onCommandBufferContentChanged));	
	}
	
	public static function initialize() : Void
	{
		if(available)
		{
			if(mInstance == null)
			{
				mInstance = new BrowserHistoryManager();
			}
		}
	}
	
	public static function get available() : Boolean
	{
		return BrowserHistory.available;
	}
	
	private function onBrowserHistoryChanged(ev) : Void 
	{
		var commandIndex : Number = parseInt(String(ev.record[COMMAND_INDEX_KEY]), 10);
		if(isNaN(commandIndex))
		{
			commandIndex = -1;
		}
		CommandManager.Instance.navigate(commandIndex);
	}
	
	/**
	 * TODO: If we need to abstract the serialization of currentCommandIndex,
	 * we can use the similar to DeepLinksSerializer approach.
	 * TODO: Can we assume that the new navigationPath will be available at this moment? 
	 * @see DeepLinksSerializer
	 */
	private function onCommandBufferContentChanged(ev) : Void 
	{
		var recordObject : Object = new Object();
		
		recordObject[COMMAND_INDEX_KEY] = ev.currentCommandIndex;
		DeepLinksSerializer.serializeCurrentNavigationPath(recordObject);
		
		BrowserHistory.Instance.addHistory(recordObject);	
	}
}